package com.booking.common.utils;

import com.booking.common.enums.BookingErrorCode;
import com.booking.common.exception.BookingException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author Qikai.Lin
 * @date 2023/4/23
 */
@Slf4j
public class DateUtils {

    public static final String TIME_FORMAT_HH_MM = "HH:mm";
    /**
     * 日期格式，年月日时分秒，年月日用横杠分开，时分秒用冒号分开
     * 例如：2005-05-10 23：20：00，2008-08-08 20:08:08
     */
    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";

    public static final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD);

    public static String dateToStr(Date date) {
        if (date == null)
            return null;
        return dateFormat.format(date);
    }

    public static Date strToDate(String timeStr) {
        Date date;
        try {
            date = dateFormat.parse(timeStr);
        } catch (ParseException e) {
            log.error("日期格式转化错误 e");
            throw new BookingException(BookingErrorCode.PARAM_ERROR.getCode(), "日期格式错误");
        }
        return date;
    }
    public static Date strToDate(String timeStr, String timeFormat) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
        return simpleDateFormat.parse(timeStr);
    }
    public static Long getDurationDays(Date begin, Date end) {
        return (end.getTime()-begin.getTime())/24/60/60/1000;
    }

    public static Date tranTimeStampToDate(long timestamp){
        return new Timestamp(timestamp);
    }

    public static LocalDateTime tranDateToLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
